<template>
  <div class="order-list-container">
    <el-card shadow="hover">
      <div slot="header" class="card-header">
        <span class="header-title">
          <i class="el-icon-s-order"></i>
          我的订单
        </span>
      </div>

      <!-- 状态筛选按钮 -->
      <div class="filter-buttons">
        <el-button
          v-for="statusItem in statusOptions"
          :key="statusItem.value"
          :type="currentStatus === statusItem.value ? 'primary' : 'default'"
          size="medium"
          @click="handleStatusFilter(statusItem.value)">
          {{ statusItem.label }}
          <el-badge 
            v-if="statusItem.value && statusCounts[statusItem.value]" 
            :value="statusCounts[statusItem.value]" 
            class="badge-item" />
        </el-button>
      </div>

      <!-- 订单列表 -->
      <div class="order-list">
        <div v-for="order in orderList" :key="order.id" class="order-card">
          <!-- 订单头部 -->
          <div class="order-header">
            <div class="order-info-left">
              <span class="order-no">订单编号：{{ order.orderNo }}</span>
              <span class="order-time">{{ formatDate(order.createTime) }}</span>
            </div>
            <div class="order-status">
              <el-tag 
                :type="getStatusType(order.status)" 
                effect="dark" 
                size="medium">
                {{ order.status }}
              </el-tag>
            </div>
          </div>

          <!-- 订单商品列表 -->
          <div class="order-products">
            <div 
              v-for="detail in order.details" 
              :key="detail.id" 
              class="product-item">
              <img 
                :src="detail.productImage" 
                :alt="detail.productName" 
                class="product-image">
              <div class="product-info">
                <div 
                  class="product-name" 
                  @click="goToProductDetail(detail.productId)">
                  {{ detail.productName }}
                </div>
                <div class="product-spec">
                  <span class="product-price">¥{{ detail.price }}</span>
                  <span class="product-quantity">x{{ detail.quantity }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 订单底部 -->
          <div class="order-footer">
            <div class="order-address">
              <i class="el-icon-location-outline"></i>
              <span>收货地址：{{ order.receiverAddress }}</span>
              <span class="receiver-info">{{ order.receiverName }} {{ order.receiverPhone }}</span>
            </div>
            <div class="order-actions">
              <div class="total-amount">
                <span class="label">订单金额：</span>
                <span class="amount">¥{{ order.totalAmount }}</span>
              </div>
              <div class="action-buttons">
                <!-- 待发货：可以取消 -->
                <el-button 
                  v-if="order.status === '待发货'" 
                  type="danger" 
                  size="small"
                  plain
                  @click="handleCancelOrder(order.id)">
                  取消订单
                </el-button>
                
                <!-- 已发货：可以收货 -->
                <el-button 
                  v-if="order.status === '已发货'" 
                  type="success" 
                  size="small"
                  @click="handleConfirmReceipt(order.id)">
                  确认收货
                </el-button>
                
                <!-- 已收货：可以评价 -->
                <el-button 
                  v-if="order.status === '已收货'" 
                  type="warning" 
                  size="small"
                  @click="handleReviewOrder(order)">
                  评价商品
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty v-if="orderList.length === 0" description="暂无订单">
          <el-button type="primary" @click="goToProductList">去购物</el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 评价弹窗 -->
    <el-dialog 
      title="评价商品" 
      :visible.sync="reviewDialogVisible" 
      width="700px"
      @close="resetReviewForm">
      <div class="review-dialog-content">
        <!-- 选择要评价的商品 -->
        <div class="product-select-section">
          <div class="section-title">请选择要评价的商品：</div>
          <div class="product-list">
            <div 
              v-for="product in currentOrderProducts" 
              :key="product.id"
              class="product-item-dialog"
              :class="{ 'selected': selectedProductId === product.productId, 'reviewed': product.reviewed }"
              @click="selectProduct(product)">
              <img :src="product.productImage" :alt="product.productName" class="product-img">
              <div class="product-name-dialog">{{ product.productName }}</div>
              <div v-if="product.reviewed" class="reviewed-badge">
                <i class="el-icon-success"></i> 已评价
              </div>
            </div>
          </div>
        </div>

        <!-- 评价表单 -->
        <el-form 
          v-if="selectedProductId" 
          :model="reviewForm" 
          :rules="reviewRules" 
          ref="reviewForm" 
          label-width="80px"
          class="review-form">
          <el-form-item label="评分" prop="rating">
            <el-rate 
              v-model="reviewForm.rating" 
              show-text 
              :texts="['极差', '失望', '一般', '满意', '惊喜']">
            </el-rate>
          </el-form-item>
          <el-form-item label="评价内容" prop="content">
            <el-input 
              type="textarea" 
              v-model="reviewForm.content" 
              :rows="6" 
              placeholder="请输入您的评价内容，分享您的使用感受..."
              maxlength="500"
              show-word-limit>
            </el-input>
          </el-form-item>
        </el-form>

        <div v-else class="select-hint">
          <i class="el-icon-info"></i>
          请先选择要评价的商品
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview" :disabled="!selectedProductId">发布评价</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserOrderList, cancelOrder, confirmReceipt } from '@/api/order';
import { createReview, checkReviewed } from '@/api/review';

export default {
  name: 'UserOrderList',
  data() {
    return {
      orderList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      currentStatus: '',
      statusOptions: [
        { label: '全部订单', value: '' },
        { label: '待发货', value: '待发货' },
        { label: '已发货', value: '已发货' },
        { label: '已收货', value: '已收货' }
      ],
      statusCounts: {},
      loading: false,
      reviewDialogVisible: false,
      currentOrderId: null,
      currentOrderProducts: [],
      selectedProductId: null,
      reviewForm: {
        rating: 5,
        content: ''
      },
      reviewRules: {
        rating: [
          { required: true, message: '请选择评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadOrderList();
    this.loadStatusCounts();
  },
  methods: {
    // 加载订单列表
    async loadOrderList() {
      this.loading = true;
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) {
          this.$router.push('/login');
          return;
        }

        const response = await getUserOrderList(
          userInfo.id, 
          this.currentPage, 
          this.pageSize, 
          this.currentStatus
        );

        if (response.data.success) {
          this.orderList = response.data.data.records || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载订单失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载订单失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },

    // 加载状态统计
    async loadStatusCounts() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) return;

        // 分别查询各状态的数量
        for (const status of ['待发货', '已发货', '已收货']) {
          const response = await getUserOrderList(userInfo.id, 1, 1, status);
          if (response.data.success) {
            this.$set(this.statusCounts, status, response.data.data.total || 0);
          }
        }
      } catch (error) {
        console.error('加载状态统计失败', error);
      }
    },

    // 状态筛选
    handleStatusFilter(status) {
      this.currentStatus = status;
      this.currentPage = 1;
      this.loadOrderList();
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        '待发货': 'warning',
        '已发货': 'primary',
        '已收货': 'success'
      };
      return statusMap[status] || 'info';
    },

    // 取消订单
    handleCancelOrder(orderId) {
      this.$confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          const response = await cancelOrder(orderId, userInfo.id);

          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '订单已取消',
              type: 'success',
              duration: 2000
            });
            this.loadOrderList();
            this.loadStatusCounts();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '取消订单失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '取消订单失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },

    // 确认收货
    handleConfirmReceipt(orderId) {
      this.$confirm('确定已收到货物吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          const response = await confirmReceipt(orderId, userInfo.id);

          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '确认收货成功',
              type: 'success',
              duration: 2000
            });
            this.loadOrderList();
            this.loadStatusCounts();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '确认收货失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '确认收货失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },

    // 跳转到商品详情
    goToProductDetail(productId) {
      this.$router.push(`/user/product-detail/${productId}`);
    },

    // 跳转到商品列表
    goToProductList() {
      this.$router.push('/user/product-list');
    },

    // 页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.loadOrderList();
    },

    // 每页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadOrderList();
    },

    // 打开评价弹窗
    async handleReviewOrder(order) {
      this.currentOrderId = order.id;
      this.currentOrderProducts = order.details.map(detail => ({
        ...detail,
        reviewed: false
      }));

      // 检查每个商品是否已评价
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      for (let product of this.currentOrderProducts) {
        try {
          const response = await checkReviewed(order.id, product.productId, userInfo.id);
          if (response.data.success) {
            product.reviewed = response.data.data;
          }
        } catch (error) {
          console.error('检查评价状态失败', error);
        }
      }

      this.reviewDialogVisible = true;
    },

    // 选择要评价的商品
    selectProduct(product) {
      if (product.reviewed) {
        this.$notify({
          title: '提示',
          message: '该商品已评价，无需重复评价',
          type: 'info',
          duration: 2000
        });
        return;
      }
      this.selectedProductId = product.productId;
    },

    // 提交评价
    submitReview() {
      if (!this.selectedProductId) {
        this.$notify({
          title: '提示',
          message: '请先选择要评价的商品',
          type: 'warning',
          duration: 2000
        });
        return;
      }

      this.$refs.reviewForm.validate(async (valid) => {
        if (valid) {
          try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const response = await createReview({
              userId: userInfo.id,
              orderId: this.currentOrderId,
              productId: this.selectedProductId,
              content: this.reviewForm.content,
              rating: this.reviewForm.rating
            });

            if (response.data.success) {
              this.$notify({
                title: '成功',
                message: '评价发布成功',
                type: 'success',
                duration: 2000
              });
              this.reviewDialogVisible = false;
              this.resetReviewForm();
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message || '发布评价失败',
                type: 'error',
                duration: 2000
              });
            }
          } catch (error) {
            this.$notify({
              title: '错误',
              message: '发布评价失败，请稍后重试',
              type: 'error',
              duration: 2000
            });
          }
        }
      });
    },

    // 重置评价表单
    resetReviewForm() {
      if (this.$refs.reviewForm) {
        this.$refs.reviewForm.resetFields();
      }
      this.currentOrderId = null;
      this.currentOrderProducts = [];
      this.selectedProductId = null;
      this.reviewForm = {
        rating: 5,
        content: ''
      };
    }
  }
};
</script>

<style scoped>
.order-list-container {
  min-height: calc(100vh - 130px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  font-size: 20px;
  margin-right: 8px;
  color: #2c5f2d;
}

/* 筛选按钮 */
.filter-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.filter-buttons .el-button {
  position: relative;
}

.badge-item {
  position: absolute;
  top: -5px;
  right: -5px;
}

/* 订单列表 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 订单卡片 */
.order-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.order-info-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.order-no {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.order-time {
  font-size: 13px;
  color: #909399;
}

.order-status {
  display: flex;
  align-items: center;
}

/* 订单商品列表 */
.order-products {
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px 0;
}

.product-item:not(:last-child) {
  border-bottom: 1px dashed #e4e7ed;
  padding-bottom: 20px;
  margin-bottom: 10px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  flex-shrink: 0;
  border: 1px solid #e4e7ed;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  cursor: pointer;
  transition: color 0.3s;
}

.product-name:hover {
  color: #2c5f2d;
}

.product-spec {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 16px;
  font-weight: 700;
  color: #f56c6c;
}

.product-quantity {
  font-size: 14px;
  color: #909399;
}

/* 订单底部 */
.order-footer {
  padding: 15px 20px;
  background: white;
}

.order-address {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
}

.order-address i {
  color: #2c5f2d;
  font-size: 16px;
}

.receiver-info {
  margin-left: auto;
  font-weight: 600;
  color: #303133;
}

.order-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-amount {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.total-amount .label {
  font-size: 14px;
  color: #606266;
}

.total-amount .amount {
  font-size: 22px;
  font-weight: 700;
  color: #f56c6c;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-buttons {
    flex-wrap: wrap;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .total-amount {
    justify-content: center;
  }

  .action-buttons {
    justify-content: center;
  }

  .product-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .product-image {
    width: 100%;
    height: auto;
  }
}

/* 评价弹窗样式 */
.review-dialog-content {
  padding: 10px 0;
}

.product-select-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.product-item-dialog {
  width: 150px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  position: relative;
}

.product-item-dialog:hover {
  border-color: #2c5f2d;
  box-shadow: 0 2px 8px rgba(44, 95, 45, 0.2);
}

.product-item-dialog.selected {
  border-color: #2c5f2d;
  background: #f0f9f0;
}

.product-item-dialog.reviewed {
  opacity: 0.6;
  cursor: not-allowed;
}

.product-img {
  width: 100%;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
  margin-bottom: 8px;
}

.product-name-dialog {
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.reviewed-badge {
  position: absolute;
  top: 5px;
  right: 5px;
  background: #67c23a;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.review-form {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.select-hint {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}

.select-hint i {
  font-size: 24px;
  margin-bottom: 10px;
  display: block;
}
</style>

